// websocket.js
export default class WebSocketService {
  constructor(url, onMessage) {
    this.url = url;
    this.ws = null;
    this.onMessage = onMessage;

    // 心跳和重连设置
    this.heartbeatInterval = 10000; // 10 秒发送一次 ping
    this.reconnectDelay = 5000;     // 5 秒后尝试重连
    this.heartbeatTimer = null;
    this.reconnectTimer = null;
    this.lockReconnect = false;     // 防止重复重连
  }

  connect() {
    if (!window.WebSocket) {
      console.error("浏览器不支持 WebSocket");
      return;
    }

    try {
      this.ws = new WebSocket(this.url);

      this.ws.onopen = () => {
        console.log("✅ WebSocket 连接成功");
        this.startHeartbeat();
      };

      this.ws.onmessage = (event) => {
        const data = JSON.parse(event.data);
        if (data.type !== "pong") {
          this.onMessage && this.onMessage(data);
        }
      };

      this.ws.onerror = (error) => {
        console.warn("❌ WebSocket 错误", error);
        this.reconnect();
      };

      this.ws.onclose = () => {
        console.warn("⚠️ WebSocket 关闭");
        this.reconnect();
      };
    } catch (e) {
      console.error("WebSocket 初始化异常", e);
      this.reconnect();
    }
  }

  send(data) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(data));
    } else {
      console.warn("WebSocket 未连接，发送失败");
    }
  }

  close() {
    clearInterval(this.heartbeatTimer);
    clearTimeout(this.reconnectTimer);
    this.ws && this.ws.close();
  }

  reconnect() {
    if (this.lockReconnect) return;
    this.lockReconnect = true;

    console.log("🔄 正在尝试重连...");
    this.reconnectTimer = setTimeout(() => {
      this.connect();
      this.lockReconnect = false;
    }, this.reconnectDelay);
  }

  startHeartbeat() {
    clearInterval(this.heartbeatTimer);
    this.heartbeatTimer = setInterval(() => {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        // this.ws.send(JSON.stringify({ type: "ping" }));
      }
    }, this.heartbeatInterval);
  }
}
